<?php

namespace app\common\library;

/**
 * 位置服务类
 */
class Location
{
    /**
     * 发送GET请求
     * @param string $url 请求URL
     * @param int $timeout 超时时间(秒)
     * @return string
     */
    protected static function curl_get($url, $timeout = 30)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    /**
     * 通过坐标获取地址信息
     * @param string $latitude 纬度
     * @param string $longitude 经度
     * @return array|false 成功返回地址信息数组,失败返回false
     */
    public static function getAddressByLocation($latitude, $longitude)
    {
        try {
            $key = config('site.qq_map_key');
            $url = "https://apis.map.qq.com/ws/geocoder/v1/?location={$latitude},{$longitude}&key={$key}";
            
            $response = self::curl_get($url);  // 修改这里，使用类内部的curl_get方法
            $result = json_decode($response, true);
            if ($result['status'] == 0) {
                return [
                    'address' => $result['result']['address'], // 完整地址
                    'formatted_address' => $result['result']['formatted_addresses']['recommend'], // 经过腾讯地图优化过的描述方式
                    'province' => $result['result']['address_component']['province'],
                    'city' => $result['result']['address_component']['city'],
                    'district' => $result['result']['address_component']['district'],
                    'street' => $result['result']['address_component']['street'],
                    'street_number' => $result['result']['address_component']['street_number']
                ];
            }
            return false;
        } catch (\think\exception\PDOException $e) {
            \think\Log::error('获取地址信息失败：' . $e->getMessage());
            return false;
        }
    }
}